package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.adaptor.Adaptor;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorXmlHandler;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Location;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

public class RunAdaptorAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/runAdaptor.do" ;

	public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
	{

		String action       = request.getParameter("action");
		HttpSession session = request.getSession ();
        User user           = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
		{
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
			return ( mapping.findForward ( "login" ) );
		}

		if( ( action == null ) || "".equalsIgnoreCase( action ) )
        {
            if ( user.getUserType() == Constants.USER_TYPE_CHIPTRAC )
            {
                return initialRequest(mapping, form, request, response);
            }
            else if ( user.getUserType() == Constants.USER_TYPE_VENDOR )
            {
                Adaptor adaptor             = null;
                String vendorNameFromXML    = null;
                String key                  = null;
                LinkedHashMap newVendorMap  = new LinkedHashMap();
                LinkedHashMap map           = getAdaptorsMap();
                Vendor vendor               = VendorDAO.getVendorDetails( user.getVendorId() );
                Iterator it                 = map.keySet().iterator();
                while( it.hasNext() )
                {
                    key = ( String ) it.next();
                    if( key != null && key.trim().length() > 0 && key.trim().indexOf(" - ") != -1 )
                    {
                        vendorNameFromXML = key.substring( 0, key.indexOf(" -") ).trim();
                    }
                    else if( key != null && key.trim().length() > 0 && key.trim().indexOf(" - ") == -1 )
                    {
                        vendorNameFromXML = key.trim();
                    }

                    if( vendorNameFromXML != null && vendorNameFromXML.trim().length() > 0 && vendorNameFromXML.equalsIgnoreCase( vendor.getVendorName() ) )
                    {
                        adaptor = ( Adaptor ) map.get( key );
                        newVendorMap.put( key, adaptor );
                    }
                }
                request.setAttribute("adaptorMap", newVendorMap );
                return ( mapping.findForward("loadFGVendorAdaptors") );

                /*Vendor vendor = null;
                vendor = VendorDAO.getVendorDetails(user.getVendorId());
                ArrayList locations = vendor.getLocationsList();
                int locationsListSize = locations != null ? locations.size() : 0;
                Location fgLocation = null;
                int fgLocationAddressId = -1;
                if ( locationsListSize > 0 )
                {
                    fgLocation = (Location)locations.get(0);
                    fgLocationAddressId = fgLocation.getAddressId();
                }
                request.setAttribute( "locationAddressId", Integer.toString( fgLocationAddressId ) );
                return initialRequestFromVendor(mapping, form, request, response);*/
            }
            else if ( user.getUserType() == Constants.USER_TYPE_CUSTOMER )
            {
                request.setAttribute("adaptorMap", new LinkedHashMap() );
                return ( mapping.findForward("loadFGVendorAdaptors") );
            }
            else if ( user.getUserType() == Constants.USER_TYPE_SALES_PERSON )
            {
                request.setAttribute("adaptorMap", new LinkedHashMap() );
                return ( mapping.findForward("loadFGVendorAdaptors") );
            }
        }
		
		if( "save".equalsIgnoreCase(action))
        {
			return saveRequest( mapping, form, request, response );
		}

        if( "runAdaptorByVendor".equalsIgnoreCase( action ) )
        {
			return initialRequestFromVendor( mapping, form, request, response );
		}

		return null;
	}
	
	public ActionForward initialRequest(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{

            ArrayList runinfoList = AdaptorRunInfo.getAdaptorRunInfoList();
            ArrayList runInfoSelectList = new ArrayList();
            Adaptor adaptor = new Adaptor();
            for( int i = 0; i < runinfoList.size(); i++ )
            {
                adaptor = ( Adaptor )runinfoList.get( i );
                runInfoSelectList.add( adaptor );
            }

            request.setAttribute( "runInfoSelectList" , runInfoSelectList );

		    request.setAttribute("adaptorList", getAdaptorsMap());
		return ( mapping.findForward("loadAdaptors") );
	}

    public ActionForward initialRequestFromVendor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{

        int locationAddressId = -1;
        ArrayList fgVendorList = null;
        try
        {
            if( request.getAttribute("locationAddressId") != null )
            {
                locationAddressId = Integer.parseInt( (String)request.getAttribute("locationAddressId") );
            }
        }catch(NumberFormatException nfe){}

        if( locationAddressId > 0 )
        {
            fgVendorList = AdaptorSetUpDAO.getFGVendorAdaptorInfo( locationAddressId , AdaptorConstants.LOCATION_TYPE_FINISHED_GOODS );
        }
		request.setAttribute("fgAdaptorList", fgVendorList );

		return ( mapping.findForward("loadFGVendorAdaptors") );
	}

	public ActionForward saveRequest(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		String[] array = request.getParameterValues("adaptorNames");
		
		if(array != null){
			LinkedHashMap map = getAdaptorsMap();
			for(int i=0; i<array.length; i++){
				//System.out.println("values = "+array[i]);
				Adaptor adaptor = (Adaptor)map.get(array[i]);
				ArrayList list = adaptor.getAdaptorList();
				Iterator it = list.iterator();
				
				while(it.hasNext()){
					//System.out.println(it.next());
				}
			}
		}else{
			
		}
		
		request.setAttribute("adaptorList", getAdaptorsMap());
		return ( mapping.findForward("loadAdaptors") );
	}
	
	public LinkedHashMap getAdaptorsMap(){
		
		LinkedHashMap map = null;
		try{
			
	    	AdaptorXmlHandler handler = new AdaptorXmlHandler();
	    	map = handler.getAdaptorList();
			/*Iterator it = map.keySet().iterator();
			while(it.hasNext()){
				String key = (String)it.next();
				//System.out.println("Key = "+key);
				Adaptor adaptor = (Adaptor)map.get(key);
				*//*ArrayList list = adaptor.getAdaptorList();
					
				Iterator its = list.iterator();
				while(its.hasNext()){
				    System.out.println(its.next());
				}*//*
			}*/
			
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	    
	    return map;
	}
}